package com.maxdu.labs.stt.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.stt.R;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;
import com.maxdu.labs.stt.constants.Constants;
import com.maxdu.labs.stt.constants.FriendRequestConstants;
import com.maxdu.labs.stt.models.FriendRequest;
import com.maxdu.labs.stt.models.db.FriendRequestDBHelper;
import com.maxdu.labs.stt.utils.FriendRequestUtils;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;

public class PendingFriendRequestActivity extends Activity {

	private TextView noPendingRequestTView;
	private ListView pendingRequestListV;
	private List<FriendRequest> pendingRequests;
	
	private ProfilePictureView profilePictureView;
	private TextView userNameView;
	
	private String currentUser;
	
	private ProgressBar spinner;
	private PendingFriendRequestAdapter adapter;
	
	private UiLifecycleHelper uiHelper;
	private Session.StatusCallback callback = new Session.StatusCallback() {
	    @Override
	    public void call(final Session session, final SessionState state, final Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_pending_friend_request);
		
		Log.w(Constants.LOG_TAG, "About to launch Session.openActiveSession()");
		Session.openActiveSession(this, true, new Session.StatusCallback() {
		    @Override
		    public void call(Session session, SessionState state, Exception exception) {
		        if(session.isOpened()) {
		            Log.w(Constants.LOG_TAG, "FB session opened successfully");
		        } else {
		        	if(exception != null){
		        		Log.w(Constants.LOG_TAG, "FB session not opened ... " + exception.toString());
		        	}
		        }
		    }
		});
		
		profilePictureView = (ProfilePictureView) findViewById(R.id.selection_profile_pic);
	    profilePictureView.setCropped(true);
	    
	    noPendingRequestTView = (TextView) findViewById(R.id.no_friend_request_to_display);
	    noPendingRequestTView.setVisibility(View.GONE);
	    
	    userNameView = (TextView) findViewById(R.id.selection_user_name);
	    pendingRequestListV = (ListView) findViewById(R.id.list_pending_request);
	    
	    
	    spinner = (ProgressBar)findViewById(R.id.progressBar1);
	    spinner.setVisibility(View.GONE);
	    
	    uiHelper = new UiLifecycleHelper(this, callback);
	    uiHelper.onCreate(savedInstanceState);
        
        pendingRequests = new ArrayList<FriendRequest>();
        adapter = new PendingFriendRequestAdapter(getApplicationContext(), R.layout.row_friendrequest, pendingRequests);
		pendingRequestListV.setAdapter(adapter);
	    
	    // Check for an open session
	    Session session = Session.getActiveSession();
	    if (session != null && session.isOpened()) {
	    	
	        // Get the user's data
	        makeMeRequest(session);
	    }
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    uiHelper.onSaveInstanceState(outState);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    uiHelper.onActivityResult(requestCode, resultCode, data);
	    
	    // Check for an open session
	    Session session = Session.getActiveSession();
	    if (session != null && session.isOpened()) {
	    	
	        // Get the user's data
	        makeMeRequest(session);
	    }
	}
	
	private void makeMeRequest(final Session session) {
	    // Make an API call to get user data and define a 
	    // new callback to handle the response.
	    Request request = Request.newMeRequest(session, 
	            new Request.GraphUserCallback() {
	        @Override
	        public void onCompleted(GraphUser user, Response response) {
	            // If the response is successful
	            if (session == Session.getActiveSession()) {
	                if (user != null) {
	                    // Set the id for the ProfilePictureView
	                    // view that in turn displays the profile picture.
	                    profilePictureView.setProfileId(user.getId());
	                    // Set the Textview's text to the user's name.
	                    userNameView.setText(user.getName());
	                    currentUser = user.getId();
	                    
	            	    GetFriendRequestsTask task = new GetFriendRequestsTask();
	            	    task.execute(user.getId());
	                }
	            }
	            if (response.getError() != null) {
	                // Handle errors, will do so later.
	            }
	        }
	    });
	    request.executeAsync();
	} 
	
	private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
	    if (session != null && session.isOpened()) {
	        // Get the user's data.
	        makeMeRequest(session);
	    }
	}
	
	
	private class GetFriendRequestsTask extends AsyncTask<String, Void, List<FriendRequest>> {

	    @Override
		protected void onPreExecute() {
			super.onPreExecute();
			spinner.setVisibility(View.VISIBLE);
		}
		
		@Override
	    protected List<FriendRequest> doInBackground(String... userIds) {

	    	if (userIds != null){
	    		//pendingRequests = FriendRequestUtils.getFriendRequestsOfAUser(userIds[0]);
	    		
	    		ParseQuery<ParseObject> query = ParseQuery.getQuery(FriendRequestDBHelper.PARSE_DB_TABLENAME_FRIENDREQUESTS);
	    		query.whereEqualTo(FriendRequestDBHelper.PARSE_DB_FIELD_RECEIVERID, userIds[0]);
	    		query.whereEqualTo(FriendRequestDBHelper.PARSE_DB_FIELD_ACCEPTED, FriendRequestConstants.FRIEND_REQUEST_PENDING);
	    		
	    		Log.d(Constants.LOG_TAG, "GetFriendRequestsTask::getFriendRequestsOfAUser:: About to try to get the friendRequests received by this user: " + userIds[0]);
	    		
	    		query.findInBackground(new FindCallback<ParseObject>() {
	    		    public void done(List<ParseObject> friendRequestList, ParseException e) {
	    		        if (e == null) {
	    		        	if (friendRequestList != null && friendRequestList.size()> 0){
	    		        		for (ParseObject userParseObject : friendRequestList){
	    		        			FriendRequest friendRequest = new FriendRequest(userParseObject.getString(FriendRequestDBHelper.PARSE_DB_FIELD_SENDERID), userParseObject.getString(FriendRequestDBHelper.PARSE_DB_FIELD_RECEIVERID));
	    		        			pendingRequests.add(friendRequest);
	    		        		}
	    		        		Log.d(Constants.LOG_TAG, "GetFriendRequestsTask::we successfully retrieved [" + pendingRequests.size()+"] pending FriendRequests for the user: " + friendRequestList.get(0).getString(FriendRequestDBHelper.PARSE_DB_FIELD_RECEIVERID));
	    		        		adapter.notifyDataSetChanged();
	    		        		spinner.setVisibility(View.GONE);
	    		        		
	    		        	}else if(friendRequestList == null){
	    		        		Log.d(Constants.LOG_TAG, "we couldn't retrieve the pending FriendRequests for the current user: users list is NULL");
	    		        	}else{
	    		        		Log.d(Constants.LOG_TAG, "we couldn't retrieve the pending FriendRequests for the current user: users list is EMPTY");
	    		        		spinner.setVisibility(View.GONE);
	    		        		noPendingRequestTView.setVisibility(View.VISIBLE);
	    		        		
	    		        	}
	    		        } else {
	    		            Log.d(Constants.LOG_TAG, "Error: " + e.getMessage());
	    		        }
	    		    }
	    		});
	    		
	    		return pendingRequests;
	    	}
	    	return null;
	    	
	    }
	}
	
	private class PendingFriendRequestAdapter extends ArrayAdapter<FriendRequest>{

		List<FriendRequest> friendRequests;
		
		public PendingFriendRequestAdapter(Context context, int resource,
				List<FriendRequest> objects) {
			super(context, resource, objects);
			
			friendRequests = objects;
		}
		
		@Override
	    public View getView(final int position, View convertView, ViewGroup parent) {
	        View view = convertView;
	        if (view == null) {
	        	LayoutInflater inflater = (LayoutInflater)getContext().getSystemService
	        		      (Context.LAYOUT_INFLATER_SERVICE);
	            view = inflater.inflate(R.layout.row_friendrequest, parent,false);
	        }

	        final FriendRequest friendRequest = friendRequests.get(position);
	        
            TextView nameTextV = (TextView) view.findViewById(R.id.friendrequest_name);
            ProfilePictureView profilePictureView = (ProfilePictureView)view.findViewById(R.id.friendrequest_picture);
            profilePictureView.setProfileId(friendRequest.getUserSenderId());
            Button btnAccept = (Button)view.findViewById(R.id.btn_accept);

            btnAccept.setOnClickListener(new OnClickListener() {
            	 
	                //Run when button is clicked
		      	  @Override
		      	  public void onClick(View v) {
		      		
		      		FriendRequestUtils.acceptFriendRequest(friendRequest.getUserSenderId(),currentUser);
		       
		      		Toast.makeText(PendingFriendRequestActivity.this, "Request accepted",
		      				Toast.LENGTH_LONG).show();
		       
		      		pendingRequests.remove(position);
		      		adapter.notifyDataSetChanged();
		      		
		      	  }
		      	});
            
            nameTextV.setText("fake name");
	        
	        return view;
	    }
	}
	
}
